import { logout } from '@/utils';
import { IS_DEV } from '@/utils/config';
import { request } from '@/utils/request';
import { useSetState } from 'ahooks';

export default () => {
  const [authState, setAuthState] = useSetState<any>({
    loading: true,
  });
  const getAuthModel = async () => {
    try {
      const res = await request('/api/auth/model');
      setAuthState({
        authModel: res,
      });
      return Promise.resolve(res);
    } catch (error) {
      console.error('获取权限模型失败', error);
      return Promise.reject(error);
    }
  };

  const getLoginUrl = async () => {
    try {
      const res = await request('/api/getAuthLoginUrl');
      setAuthState(res || {});
      return Promise.resolve(res);
    } catch (error) {
      console.error('获取登录URL失败', error);
      return Promise.reject(error);
    }
  };

  const getUserInfo = async () => {
    try {
      const res = await request('/api/userInfo');
      setAuthState({
        userInfo: res,
      });
      return Promise.resolve(res);
    } catch (error) {
      console.error('获取用户信息失败', error);
      return Promise.reject(error);
    }
  };

  const getNavbar = async () => {
    try {
      const res = await request('/api/navbar');
      const authList: any[] = [];
      const navbar = res?.filter?.((navItem: any) => {
        const { child, url } = navItem || {};
        const testUrl = url.startsWith('/') ? url : '/' + url;
        if (testUrl === '/auth') {
          Array.isArray(child) && authList.push(...child);
          return false;
        }
        return true;
      });
      setAuthState({
        navbar,
        authList,
      });
      return Promise.resolve(res);
    } catch (error) {
      console.error('获取导航栏失败', error);
      return Promise.reject(error);
    }
  };

  /**
   * All001 / Ab1234567
   */
  const getAuthInfo = async () => {
    try {
      const authModel = await getAuthModel();
      if (authModel === 2 && !IS_DEV) {
        const loginData = await getLoginUrl();
        const userInfo = await getUserInfo();
        if (!userInfo) {
          logout(loginData.appLoginUrl);
        } else {
          await getNavbar();
        }
      }
    } finally {
      setAuthState({
        loading: false,
      });
    }
  };

  return {
    authState,

    getAuthInfo,
    getLoginUrl,
    getAuthModel,
  };
};
